import { defineStore } from 'pinia'
import { login, getUserInfo } from '@/api/user'
import { setToken, getToken } from '@/utils/auth'
import { getRandomColor } from '@/utils/globalMethod'
import { routeSub } from '@/utils/pages'

export const userStore = defineStore('user', {
    state: () => ({
        token: getToken() || null,
        profile: JSON.parse(localStorage.getItem('profile')) || {},
        auth: {},
        used: []
    }),
    getters: {

    },
    actions: {
        async changeUserInfo(payload) {
            const { token, profile } = await login(payload)
            if (token) {
                setToken(token)
                this.profile = profile
                localStorage.setItem('profile', JSON.stringify(profile)) // 添加路由表 --路由中使用
                return true
            } else {
                return false
            }
        },

        /**
         * @description: 将目标路由添加到对应的本地key中
         * @summary:忽略条件：白名单路由、没有name、内置静态路由
         * @param {Object} payload：目标路由对象
         * @return {void}
         */
        joinToUsed(payload) {

            const { meta, path, name } = payload

            const whiteMenu = ['/dashboard', '/404']

            if (whiteMenu.includes(path)) return

            if (!name || routeSub.find(item => item.name === name)) return

            const index = this.used.findIndex(item => item.path === path)

            if (index === -1) {
                this.used.push({ title: meta.title, path, count: 1, color: getRandomColor() })
            } else {
                this.used[index].count++
            }

            const key = `used_${this.profile.userID}`

            localStorage.setItem(key, JSON.stringify(this.used))

        },

        /* 初始化used数据 */
        usedInfo() {
            const key = `used_${this.profile.userID}`
            this.used = localStorage.getItem(key) ? JSON.parse(localStorage.getItem(key)) : []
        },

        async loadUserInfo() {
            const { data } = await getUserInfo({ userID: this.profile.userID })
            this.profile = data
            localStorage.setItem('profile', JSON.stringify(data))
        },
    }
})
